package com.wrupple.vegetate.server.integration.impl;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gwt.event.shared.EventBus;
import com.wrupple.muba.common.client.application.DataCallback;
import com.wrupple.muba.common.shared.StateTransition;
import com.wrupple.vegetate.domain.exceptions.IntegrationLayerException;
import com.wrupple.vegetate.server.VegetateServiceLocator;
import com.wrupple.vegetate.server.integration.HttpServletRequestHandler;
import com.wrupple.vegetate.server.integration.HttpServletResponseHandler;
import com.wrupple.vegetate.server.process.VegetateRequestHandlingProcess;

public class ProcessDelegatingRequestHandler implements
		HttpServletRequestHandler {
	
	class WriteResponse extends DataCallback<HttpServletResponseHandler>{
		HttpServletResponse resp;
		
		public WriteResponse(HttpServletResponse resp) {
			super();
			this.resp = resp;
		}

		@Override
		public void execute() {
			try {
				result.handleResponse(resp);
			} catch (Exception e) {
				System.err.println(e+Arrays.toString(e.getStackTrace()));
				resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			} 
		}
		
	}
	
	VegetateRequestHandlingProcess<?> delegate;
	VegetateServiceLocator childServiceLocator;
	EventBus bus;

	public ProcessDelegatingRequestHandler(EventBus bus,
			VegetateRequestHandlingProcess<?> delegate,
			VegetateServiceLocator childServiceLocator) {
		super();
		this.bus=bus;
		this.delegate = delegate;
		this.childServiceLocator = childServiceLocator;
	}

	@Override
	public void handleRequest(HttpServletRequest req, HttpServletResponse resp, Map<String, String> pathParameters)
			throws IOException, IntegrationLayerException {
		StateTransition<HttpServletResponseHandler> onDone = new WriteResponse(resp);
		delegate.getInterpret().setPathParameters(pathParameters);
		delegate.start(req, onDone, bus);
	}

	@Override
	public VegetateServiceLocator getChildServiceLocator() {
		return childServiceLocator;
	}

}
